<template>
  <t-card :bordered="false">
    <div class="top-right">
    <t-button theme="primary" @click="formRef?.submit" v-permission="['system:engineering-accounting-expenses:start-settlement-approval']" v-if="result == null || result == 3|| result == 4">
      提交审核
    </t-button>
    <span v-if="result" style="margin-left: var(--td-comp-margin-s)"
        ><t-tag :theme="getTagThemeAndLabel(result - 1).theme">{{
          getTagThemeAndLabel(result - 1).label
        }}</t-tag>
      </span>
    <settlement-expenses :order-id="orderId"/>
    </div>
    <!-- 自定义表格 -->
    <t-form ref="formRef" :data="formDataT" reset-type="initial" @submit="handleApprove">
    <t-table 
      row-key="index" 
      :data="tableData"  
      size="small"
      stripe 
      bordered 
      :columns="columns">
      <template #money="{ row, rowIndex }">
        <t-form-item
          label="金额"
          :name="`tableData[${rowIndex}].money`"
          :rules="[
            { 
              required: true, 
              message: '请填写金额',
              validator: (val) => val !== null && val !== undefined && val !== '',
            },
          ]"
          label-width="0"
        >
          <t-input-number v-model:value="row.money"  :readonly="result == 2 || result == 1" clearable :min="0" />
        </t-form-item>
      </template>
      <template #teamUserId="{ row }">
          <t-link theme="primary" v-permission="['system:engineering-team-users:query']"
            @click="handleOpenDialog('update', { id: row.teamId,teamUserId: row.teamUserId, engineeringNode: row.stageType})">
            {{ row.teamUserId ? teamUserNames[row.teamUserId] : '' }}
          </t-link>
      </template>
      <template #operation="{ row }">
        <t-space break-line>
          <t-popconfirm content="确认要提交该项金额吗？"
            v-if="!row.id"
            @confirm="handleConfirmComplete({ name: row.name, engineeringId: engineeringId, money: row.money, stageType: row.stageType,status:'1',dictReamrk:row.dictReamrk})">
            <t-link theme="primary" v-permission="['system:engineering-accounting-expenses:create']" > 确认 </t-link>
          </t-popconfirm>
          <t-popconfirm content="确认要修改该项金额吗？"
            v-else
            :disabled="result == 2 || result == 1"
            @confirm="handleUpdate({ name: row.name, engineeringId: engineeringId, money: row.money, stageType: row.stageType,status:'1',dictReamrk:row.dictReamrk,id:row.id})">
            <t-link theme="primary" :disabled="result ==2 || result ==1" v-permission="['system:engineering-accounting-expenses:update']" > 修改 </t-link>
          </t-popconfirm>
        </t-space>
      </template>
    </t-table>
  </t-form>
    <!-- 自定义对话框 -->
  <custom-dialog ref="customDialogRef" 
    v-slot="{ formData }" 
    :api-map="{get:engineeringStageListCRUD.get,update:engineeringStageUpdateTeam}" 
    header="*施工节点" 
    :on-before-save-data="handleDialogSaveData" 
    @request-success="handleDialogRequestSuccess"
  >
    <t-form-item label="施工班组" name="teamUserId" :rules="[{ required: true, message: '请选择施工班组' }]" v-if="!isTime">
      <t-select v-model:value="formData.teamUserId" :options="teamUserOptions" :keys="{ label: 'name', value: 'id' }"
        placeholder="请选择施工班组" clearable filterable @clear="formData.teamUserId = null" />
    </t-form-item>

  </custom-dialog>


  </t-card>
   <!-- 粘性审批对话框 -->
   <sticky-approve-dialog ref="stickyApproveDialogRef22" :order-id="orderId" approve-type="22" />
</template>


<script setup lang="ts">
import dayjs from 'dayjs';
import { FormInstanceFunctions, MessagePlugin, SubmitContext, TableCol } from 'tdesign-vue-next';
import { computed, inject, onMounted, Ref, ref, useTemplateRef } from 'vue';

import { productContractCRUD, updateProductContractProgress } from '@/api/order/product';
import CustomTable from '@/components/custom/table/index.vue';
import CustomDialog from '@/components/custom/dialog/index.vue';

import StickyApproveDialog from '@/pages/approve/components/sticky-approve-dialog .vue';
import { engineeringStageListCRUD, engineeringStageConfirmComplete ,engineeringStageUpdateTeam, engineeringStageTimeTempCRUD } from '@/api/project/details';
import SettlementExpenses from './SettlementExpenses.vue'
import { useDictionaryStore } from '@/store';
import { engineeringAccountingCRUD, startSettlementApproval } from '@/api/project/engineering';
import { engineeringTeamCRUD } from '@/api/config/common-config';

interface TagThemeAndLabel {
  theme: 'warning' | 'success' | 'danger' | 'default';
  label: string;
}
// 定义 props
const props = defineProps({
  injectKey: {
    type: String,
    default: 'engineeringDetails',
  },
});
// 字典仓库
const dictionaryStore = useDictionaryStore();
// 默认的注入键
const injectKey = props.injectKey
// 动态注入数据
const details = inject<Ref<Record<string, any>>>(injectKey);
// 施工详情
const engineeringDetails = details;
const engineeringId = details.value.engineeringId || details.value.id
const orderId = details.value.orderId || details.value.id

  const formRef = useTemplateRef<FormInstanceFunctions>('formRef');
// columns
const columns: TableCol[] = [
  { colKey: 'name', title: '项目' },
  { colKey: 'teamUserId', title: '班组' },
  { colKey: 'money', title: '金额' },
  { colKey: 'operation', title: '操作', fixed: 'right' },
].map(column => ({ ...column, align: 'center' }));
const result = ref()
const tableData = ref([])
// 添加表单数据
const formDataT = ref({ tableData: [] });
// 处理获取合同详情
const handleGetContractDetails = () => {
  const params = {
    orderId: orderId,
    engineeringId: engineeringId,
  };
  engineeringAccountingCRUD.page(params)
    .then((data) => {
      result.value = data?.result 
      const {page , team} = data
      // 创建一个以 stageType 为键的映射，方便查找
      const stageMoneyMap: Record<string, number> = {};
      if(page?.total>0) {
        page.list.forEach((item:any) => {
          stageMoneyMap[item.stageType] = item;
        });
        console.log(stageMoneyMap,'stageMoneyMap')
      }
          // 创建 team 数据的映射表，以 engineeringNode 为键
      const teamMap: Record<string, any> = {};
      if(team && team.length > 0) {
        team.forEach((teamItem: any) => {
          teamMap[teamItem.engineeringNode] = {
            teamUserId: teamItem.teamUserId,
            teamId: teamItem.id
          };
        });
      }

       // 生成表格数据，并根据 stageType 填充对应的金额和班组信息
      tableData.value = dictionaryStore.get('construction_settlement_type').map((item, index) => {
        const existingRecord = stageMoneyMap[item.value];
        const teamInfo = teamMap[item.value]; // 根据 stageType 查找对应的班组信息
        
        return {
          index, // 唯一标识
          name: item.label, // 进度名称
          stageType: item.value,
          money: existingRecord?.money, // 从映射中获取金额，如果没有则为空
          dictReamrk: item.remark,
          id: existingRecord?.id,
          status: existingRecord?.status,
          // 添加班组信息
          teamUserId: teamInfo?.teamUserId || null,
          teamId: teamInfo?.teamId || null
        };
      });
      
      formDataT.value.tableData = tableData.value;
      initializeTeamUserNames(tableData.value);
      
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
// 施工班组名称映射表
const teamUserNames = ref<Record<string, string>>({});
// 获取施工班组名称
const getTeamUserName = (teamUserId: string, engineeringNode: string) => {
  const params = {
    pageSize: -1,
    jobType: engineeringNode,
    companyId: engineeringDetails.value.companyId,
  };
  engineeringTeamCRUD.page(params).then((data) => {
    const teamUserObj = data.list.find((o: any) => o.id === teamUserId);
    if (teamUserObj) {
      // 将施工班组名称存储到映射表中
      teamUserNames.value[teamUserId] = teamUserObj.name;
    }
  }).catch(({ message }) => {
    MessagePlugin.error(message);
  });
};
// 初始化施工班组名称
const initializeTeamUserNames = (list: any[]) => {
  list.forEach((item) => {
    if (item.teamUserId) {
      getTeamUserName(item.teamUserId, item.stageType);
    }
  });
};
onMounted(() => {
  handleGetContractDetails()
});
// 根据审批状态获取标签样式以及文字
const getTagThemeAndLabel = (result: number): TagThemeAndLabel => {
  const map: TagThemeAndLabel[] = [
    {
      theme: 'warning',
      label: '待审批',
    },
    {
      theme: 'success',
      label: '审批通过',
    },
    {
      theme: 'danger',
      label: '审批不通过',
    },
    {
      theme: 'danger',
      label: '审批已取消',
    },
  ];

  return result in map ? map[result] : { theme: 'default', label: '未知状态' };
};
// 处理确认完成
const handleConfirmComplete = (params: Record<string, any>) => {
  if(params.money === null || params.money === undefined ||params.money  === '') {
    MessagePlugin.error('请先填写金额');
    return
  }
  const { name, ...rest } = params;
  engineeringAccountingCRUD.create({ ...rest })
    .then(() => {
      MessagePlugin.success(`${params.name}金额提交完成`);
      handleGetContractDetails()
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
// 修改金额
const handleUpdate = (params: Record<string, any>) => {
  const { name, ...rest } = params;
  engineeringAccountingCRUD.update({ ...rest })
    .then(() => {
      MessagePlugin.success(`${params.name}金额修改完成`);
      handleGetContractDetails()
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
// 添加计算属性检查是否可以提交
const canSubmit = computed(() => {
  return tableData.value.every(row => {
    const id = row.id;
    return id !== '' && 
           id !== null && 
           id !== undefined 
  });
});
// 提交审批
const handleApprove = ({ validateResult }: SubmitContext) => {
  if (validateResult !== true) return;
  if (!canSubmit.value) {
    MessagePlugin.error('请确认所有有效金额后再提交审核');
    return;
  }
  const params = {
    orderId: orderId,
    engineeringId: engineeringId,
  }
  startSettlementApproval(params).then(() => {
      MessagePlugin.success('提交成功');
      handleGetContractDetails()
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
}
// 粘性审批对话框ref
const stickyApproveDialogRef22 = useTemplateRef('stickyApproveDialogRef22');
onMounted(() => {
  // const { approveType } = orderDetails.value;
  stickyApproveDialogRef22.value.open();
});
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  getTeamUserOptionList(params.engineeringNode);
  console.log(params,'ppp');
  
  customDialogRef.value.open(mode, params);
};
const getTeamUserOptionList = (engineeringNode: string | Number) => {

  const params = {
    pageSize: -1,
    jobType: engineeringNode,
    companyId: engineeringDetails.value.companyId
  }
  engineeringTeamCRUD.page(params).then(data => {
    teamUserOptions.value = data.list
  }).catch(({ message }) => {
    MessagePlugin.error(message);
  });

}
// 施工班组option
const teamUserOptions = ref([])
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  handleGetContractDetails()
};
// 处理对话框保存数据
const handleDialogSaveData = (params: Record<string, any>) => {
  if (params.fileUrl) {
    delete params.fileUrl
  }
};
</script>
<style scoped>
/* 让校验信息显示在右侧 */
:deep(.t-input__extra) {
  bottom: 4px !important;
  margin-left: 146px;
  max-width: 24%;
}
.top-right {
  display: flex;
  margin-bottom: 10px;
  align-items: center;
}
</style>
